<template>
  <view>
    <!-- 导航栏 -->
    <hi-navbar
      fixed
      back
      transparent="show"
      :backgroundColor="[237, 240, 243]"
      title="我的收藏"
    >
    </hi-navbar>

    <div v-if="list.length !== 0">
      <!-- 试卷列表 -->
      <question-list
        :question-list="list"
        :canSelect="false"
        @collect="$_onCollectQuestion"
        @answer="onAnswer"
      ></question-list>
    </div>
    <image
      src="/static/image/home/empty.jpg"
      mode="widthFix"
      v-else
      class="emptyimg"
    ></image>
  </view>
</template>

<script>
import QuestionList from "_c/Question/QuestionList"
import { mapActions } from "vuex"
import func from "_u/func"

export default {
  components: { QuestionList },

  data() {
    return {
      list: [],
    }
  },

  mounted() {
    this.getAllCollectList()
  },

  onPageScroll(e) {
    this.isShowBorder = e.scrollTop !== 0
  },

  methods: {
    // 获取所有收藏题目
    async getAllCollectList() {
      uni.showLoading({ title: "加载中..." })

      let QuestionCollect = new wx.BaaS.TableObject("question_collect")
      let collectList = await QuestionCollect.limit(200)
        .expand(["question", "paper"])
        .find()

      collectList = collectList.data.objects.map((item) => {
        return Object.assign(
          {
            isCollected: true,
            collectId: item.id,
            paperTitle: item.paper.title,
            paperCreateAt: item.created_at,
          },
          item.question
        )
      })

      this.list = collectList
      uni.hideLoading()
    },

    // 取消收藏题目
    $_onCollectQuestion(collectIndex) {
      const QuestionCollect = new wx.BaaS.TableObject("question_collect")
      QuestionCollect.delete(this.list[collectIndex]["collectId"])

      // 更新错误表中的
      const QuestionError = new wx.BaaS.TableObject("question_error")
      let Question = new wx.BaaS.TableObject("question")
      let query = new wx.BaaS.Query()
      query.compare(
        "question",
        "=",
        Question.getWithoutData(this.list[collectIndex]["id"])
      )
      let records = QuestionError.limit(10).offset(0).getWithoutData(query)

      records.set("isCollected", false)
      records.update()

      this.list.splice(collectIndex, 1)
      uni.showToast({ title: "已取消收藏!", icon: "none" })
    },

    onAnswer(index) {
      const selectItem = this.list[index]
      this.$set(this.list, index, {
        ...selectItem,
        isShowAnswer: !selectItem.isShowAnswer,
      })
    },
  },
}
</script>

<style lang="scss" scope>
.emptyimg {
  position: absolute;
  bottom: 0;
  left: 0;

  width: 100%;
}
</style>
